/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.KDniao.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticsThreeParty;
import com.thinkgem.jeesite.modules.KDniao.entity.requestKDniao.responseKDniaoTraces;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticsThreePartyService;
import com.thinkgem.jeesite.modules.KDniao.service.meRequest.KdApiOrderDistinguish;
import com.thinkgem.jeesite.modules.KDniao.unit.CacheUtils;

/**
 * 快递鸟接口配置信息Controller
 * @author Owen
 * @version 2017-04-05
 */
@Controller
@RequestMapping(value = "${adminPath}/kdniaocommonpojo/logisticsThreeParty")
public class LogisticsThreePartyController extends BaseController {

	@Autowired
	private LogisticsThreePartyService logisticsThreePartyService;

    @Autowired
    private KdApiOrderDistinguish kdApiOrderDistinguish;

	@ModelAttribute
	public LogisticsThreeParty get(@RequestParam(required=false) String id) {
		LogisticsThreeParty entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisticsThreePartyService.get(id);
		}
		if (entity == null){
			entity = new LogisticsThreeParty();
		}
		return entity;
	}
	
	@RequiresPermissions("kdniaocommonpojo:logisticsThreeParty:view")
	@RequestMapping(value = {"list", ""})
	public String list(LogisticsThreeParty logisticsThreeParty, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisticsThreeParty> page = logisticsThreePartyService.findPage(new Page<LogisticsThreeParty>(request, response), logisticsThreeParty); 
		model.addAttribute("page", page);
        return "modules/logistics/logisticsThreePartyList";
	}

	@RequiresPermissions("kdniaocommonpojo:logisticsThreeParty:view")
	@RequestMapping(value = "form")
	public String form(LogisticsThreeParty logisticsThreeParty, Model model) {
		model.addAttribute("logisticsThreeParty", logisticsThreeParty);
        return "modules/logistics/logisticsThreePartyForm";
	}

    @SuppressWarnings({ "unchecked" })
    @RequiresPermissions("kdniaocommonpojo:logisticsThreeParty:edit")
	@RequestMapping(value = "save")
	public String save(LogisticsThreeParty logisticsThreeParty, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, logisticsThreeParty)){
			return form(logisticsThreeParty, model);
		}
        logisticsThreePartyService.save(logisticsThreeParty);
        //重新写入缓存
        List<LogisticsThreeParty> lks = (List<LogisticsThreeParty>) CacheUtils.get("LogisticsThreePartyisenadleList");
        if (lks != null && lks.size() > 0) {
            boolean flag = true;
            for (int i = 0; i < lks.size(); i++) {
                LogisticsThreeParty threeParty = lks.get(i);
                if (threeParty.getId().equals(logisticsThreeParty.getId())) {
                    lks.remove(i);
                    lks.add(logisticsThreeParty);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                if ("1".equals(logisticsThreeParty.getIsenadle()))
                    lks.add(logisticsThreeParty);
            }
            CacheUtils.remove("LogisticsThreePartyisenadleList");
            CacheUtils.put("LogisticsThreePartyisenadleList", lks);
            logger.info("LogisticsThreePartyisenadleList+++++++写入缓存成功");
        }
        writeCache(logisticsThreeParty);
		addMessage(redirectAttributes, "保存快递鸟配置成功");
		return "redirect:"+Global.getAdminPath()+"/kdniaocommonpojo/logisticsThreeParty/?repage";
	}
	
    @SuppressWarnings({ "unchecked" })
    @RequiresPermissions("kdniaocommonpojo:logisticsThreeParty:edit")
	@RequestMapping(value = "delete")
    public String delete(LogisticsThreeParty logisticsThreeParty, RedirectAttributes redirectAttributes) {

        logisticsThreePartyService.updateisenadle(logisticsThreeParty);
        if ("0".equals(logisticsThreeParty.getIsenadle())) {
            //重新写入缓存
            List<LogisticsThreeParty> lks = (List<LogisticsThreeParty>) CacheUtils.get("LogisticsThreePartyisenadleList");
            if (lks != null && lks.size() > 0) {
                boolean fals = false;
                for (int i = 0; i < lks.size(); i++) {
                    LogisticsThreeParty threeParty = lks.get(i);
                    if (threeParty.getId().equals(logisticsThreeParty.getId())) {
                        lks.remove(i);
                        fals = true;
                        break;
                    }
                }
                if (fals) {
                    CacheUtils.remove("LogisticsThreePartyisenadleList");
                    CacheUtils.put("LogisticsThreePartyisenadleList", lks);
                    logger.info("LogisticsThreePartyisenadleList+++++++写入缓存成功");
                }
            }
            addMessage(redirectAttributes, "禁用快递鸟配置成功");
        } else {
            addMessage(redirectAttributes, "启用快递鸟配置成功");
            CacheUtils.remove("LogisticsThreePartyisenadleList");
        }

		return "redirect:"+Global.getAdminPath()+"/kdniaocommonpojo/logisticsThreeParty/?repage";
	}

    @RequestMapping("Verification")
    @ResponseBody
    public Map<Object, Object> Verification(@Param("companys") String companys, @Param("codes") String codes) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        String company = "";
        try {
            String result = kdApiOrderDistinguish.getOrderTracesByJson(codes);
            if (result == null || "".equals(result)) {
                map.put("Verification", "快递单号有错");
                return map;
            }
            JsonMapper mapper = new JsonMapper();
            responseKDniaoTraces dniaoTraces = mapper.readValue(result, responseKDniaoTraces.class);
            if (dniaoTraces.getShippers() != null && dniaoTraces.getShippers().size() > 0)
                company = dniaoTraces.getShippers().get(0).getShipperCode();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (company == null || "".equals(company)) {
            map.put("Verification", "快递单号有错");
            return map;
        }
        if (company.equals(companys)) {
            map.put("Verification", true);
            return map;
        } else {
            map.put("Verification", "物流公司与快递单号不一致");
            return map;
        }
    }

    @SuppressWarnings("unchecked")
    public void writeCache(LogisticsThreeParty logisticsThreeParty) {
        //重新写入缓存
        List<LogisticsThreeParty> lks = (List<LogisticsThreeParty>) CacheUtils.get("LogisticsThreePartyisenadleallListDesc");
        if (lks != null && lks.size() > 0) {
            boolean flag = true;
            for (int i = 0; i < lks.size(); i++) {
                //如果是修改数据
                LogisticsThreeParty threeParty = lks.get(i);
                if (threeParty.getId().equals(logisticsThreeParty.getId())) {
                    lks.remove(i);
                    lks.add(logisticsThreeParty);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                //如果是添加数据
                lks.add(logisticsThreeParty);
            }
            CacheUtils.remove("LogisticsThreePartyisenadleallListDesc");
            CacheUtils.put("LogisticsThreePartyisenadleallListDesc", lks);
            logger.info("LogisticsThreePartyisenadleallListDesc+++++++写入缓存成功");
        }
    }
}